package com.cskaoyan.wordmemorize.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLogConstant;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.common.exception.ExcelParseException;
import com.cskaoyan.wordmemorize.converter.VocConverter;
import com.cskaoyan.wordmemorize.dao.entity.*;
import com.cskaoyan.wordmemorize.dao.mapper.*;
import com.cskaoyan.wordmemorize.dto.admin.*;
import com.cskaoyan.wordmemorize.dto.app.DisplayBookVocDTO;
import com.cskaoyan.wordmemorize.dto.app.DisplayChapterDTO;
import com.cskaoyan.wordmemorize.dto.app.UserBookStatisticsDTO;
import com.cskaoyan.wordmemorize.dto.app.UserExampleSentenceDTO;
import com.cskaoyan.wordmemorize.request.*;
import com.cskaoyan.wordmemorize.service.VocService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class VocServiceImpl implements VocService {

    @Autowired
    VocMapper vocMapper;
    @Autowired
    VocConverter vocConverter;
    @Autowired
    VocMeaningMapper vocMeaningMapper;
    @Autowired
    ExampleSentenceMapper exampleSentenceMapper;
    @Autowired
    VocChapBookMapper vocChapBookMapper;
    @Autowired
    VocChapterMapper vocChapterMapper;
    @Autowired
    VocBookMapper vocBookMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserVocExampleSentenceMapper userVocExampleSentenceMapper;
    @Autowired
    UserFavoriteMapper userFavoriteMapper;


    @Override
    public PageDTO<VocDTO> getVocabularies(VocPageRequest pageQuery) {
        if(pageQuery.getPageNum() == null){
            List<VocDO> vocDOS = vocMapper.selectList(null);
            return vocConverter.vocList2Page(vocDOS, (long) vocDOS.size());
        }
        Page<VocDO> pageParam = new Page<>(pageQuery.getPageNum(), pageQuery.getCount());

        Long bookId = (pageQuery.getBookId() != null) ? Long.parseLong(pageQuery.getBookId()) : null;
        Long chapterId = (pageQuery.getChapterId() != null) ? Long.parseLong(pageQuery.getChapterId()) : null;

        Page<VocDO> vocDOPage = vocMapper.getVocabularyInfo(bookId, chapterId, pageQuery.getKeyword(), pageParam);
        return vocConverter.vocList2Page(vocDOPage.getRecords(), vocDOPage.getTotal());
    }
    @Transactional
    @Override
    @OperateLog(dateType = "词汇", operateType = OperateLogConstant.OPERATE_ADD)
    public void addVoc(VocCommand command) {
        if (command==null)
            return;
        // 判断要添加的单词是否存在
        LambdaQueryWrapper<VocDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VocDO::getContent, command.getContent());

        VocDO vocDO = vocMapper.selectOne(queryWrapper);
        if (vocDO != null) {
            throw new BusinessException(ResultCodeEnum.VOC_EXISTED);
        }

        // 保存单词
        VocDO voc = vocConverter.command2VocDO(command);
        // 保存基本的单词数据
        vocMapper.insert(voc);


        // 保存单词释义
        List<VocMeaningCommand> interpretations = command.getInterpretations();
        List<VocMeaningDO> vocMeaningDOs = vocConverter.commands2VocMeaningDOs(interpretations);

        if (!CollectionUtils.isEmpty(vocMeaningDOs)) {

            vocMeaningDOs.forEach(vocMeaningDO -> {

                // 设置释义多对应的单词id
                vocMeaningDO.setVocId(voc.getId());
                vocMeaningMapper.insert(vocMeaningDO);
            });
        }

        // 保存例句
        List<ExampleSentenceCommand> examples = command.getExamples();
        List<ExampleSentenceDO> exampleSentenceDOs = vocConverter.commands2ExampleSentenceDOs(examples);
        if (!CollectionUtils.isEmpty(exampleSentenceDOs)) {
            exampleSentenceDOs.forEach(exampleSentenceDO -> {

                // 设置例句对应的单词id
                exampleSentenceDO.setVocId(voc.getId());
                exampleSentenceMapper.insert(exampleSentenceDO);
            });
        }


        // 保存单词-章节-书籍关系
        List<VocChapBookCommand> relations = command.getRelations();
        List<VocChapBookDO> vocChapBookDOs = vocConverter.commands2VocChapBookDOs(relations);
        if (!CollectionUtils.isEmpty(vocChapBookDOs)) {
            vocChapBookDOs.forEach(vocChapBookDO -> {

                // 设置单词id
                vocChapBookDO.setVocId(voc.getId());
                vocChapBookMapper.insert(vocChapBookDO);


                //修改章节中包含的单词数量
                if (vocChapBookDO.getChapterId() != null) {

                    LambdaUpdateWrapper<VocChapterDO> chapterWrapper = new LambdaUpdateWrapper<>();
                    chapterWrapper.eq(VocChapterDO::getId, vocChapBookDO.getChapterId())
                            .setSql("voc_count = voc_count + 1");
                    vocChapterMapper.update(null, chapterWrapper);

                }

                // 书籍中包含的单词数量
                LambdaUpdateWrapper<VocBookDO> vocBookWrapper = new LambdaUpdateWrapper<>();
                vocBookWrapper.eq(VocBookDO::getId, vocChapBookDO.getBookId())
                        .setSql("voc_count = voc_count + 1");

                vocBookMapper.update(null, vocBookWrapper);
            });
        }

    }
   @Transactional
   @OperateLog(dateType = "单词",operateType =OperateLogConstant.OPERATE_UPDATE_STATUS )
    @Override
    public void updateVoc(VocCommand command) {
        //更新单词表

        VocDO vocDO = vocConverter.command2VocDO(command);
        LambdaQueryWrapper<VocDO> vocDOWrapper = new LambdaQueryWrapper<>();
        vocDOWrapper.eq(VocDO::getContent, vocDO.getContent());
        VocDO selectvocDO = vocMapper.selectOne(vocDOWrapper);
        if (selectvocDO == null) {
            throw new BusinessException(ResultCodeEnum.VOC_NOT_EXISTED);
        }
        LambdaUpdateWrapper<VocDO> vocDOUpdateWrapper = new LambdaUpdateWrapper<>();
        vocDOUpdateWrapper.eq(VocDO::getContent, vocDO.getContent());
        vocMapper.update(vocDO, vocDOUpdateWrapper);
        //单词id
        Long id = selectvocDO.getId();

        //修改单词释义
        List<VocMeaningCommand> interpretations = command.getInterpretations();
        List<VocMeaningDO> convertVocMeaningDOs = vocConverter.commands2VocMeaningDOs(interpretations);
        LambdaQueryWrapper<VocMeaningDO> vocMeaningDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vocMeaningDOLambdaQueryWrapper.eq(VocMeaningDO::getVocId, id);
        //查询出来的释义包含id和vocid
        List<VocMeaningDO> selectVocMeaningDOS = vocMeaningMapper.selectList(vocMeaningDOLambdaQueryWrapper);
        //stream流筛选出数据库中需要删除的释义
        List<VocMeaningDO> deleteList = selectVocMeaningDOS.stream()
                .filter(vocMeaningDO -> convertVocMeaningDOs.stream()
                        .noneMatch(convertDO ->
                                Objects.equals(vocMeaningDO.getType(), convertDO.getType()) &&
                                        Objects.equals(vocMeaningDO.getInterContent(), convertDO.getInterContent())
                        )
                ).collect(Collectors.toList());
        ArrayList<Long> longs = new ArrayList<>();
        for (VocMeaningDO meaning : deleteList) {
            longs.add(meaning.getId());
        }
        //stream流筛选出需要添加的释义
        List<VocMeaningDO> addList = convertVocMeaningDOs.stream()
                .filter(vocMeaningDO -> selectVocMeaningDOS.stream()
                        .noneMatch(convertDO ->
                                Objects.equals(vocMeaningDO.getType(), convertDO.getType()) &&
                                        Objects.equals(vocMeaningDO.getInterContent(), convertDO.getInterContent())
                        )
                ).collect(Collectors.toList());
        //删除释义
        vocMeaningMapper.deleteByIds(longs);
        //添加释义
        if (!CollectionUtils.isEmpty(addList)) {
            addList.forEach((vocMeaningDO -> {
                vocMeaningDO.setVocId(id);
                vocMeaningMapper.insert(vocMeaningDO);
            }));
        }

        //修改例句
        List<ExampleSentenceCommand> examples = command.getExamples();
        List<ExampleSentenceDO> convertExampleSentenceDOs = vocConverter.commands2ExampleSentenceDOs(examples);
        LambdaQueryWrapper<ExampleSentenceDO> exampleSentenceDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        exampleSentenceDOLambdaQueryWrapper.eq(ExampleSentenceDO::getVocId, id);
        //查询出来的释义包含id和vocid
        List<ExampleSentenceDO> selectSentenceDOList = exampleSentenceMapper.selectList(exampleSentenceDOLambdaQueryWrapper);
        //stream流筛选出数据库中需要删除的释义
        List<ExampleSentenceDO> deleteSentenceList = selectSentenceDOList.stream()
                .filter(exampleSentenceDO -> convertExampleSentenceDOs.stream()
                        .noneMatch(convertDO ->
                                Objects.equals(exampleSentenceDO.getContent(), convertDO.getContent()) &&
                                        Objects.equals(exampleSentenceDO.getMeaning(), convertDO.getMeaning())
                        )
                ).collect(Collectors.toList());
        ArrayList<Long> sentenceList = new ArrayList<>();
        for (ExampleSentenceDO sentenceDO : deleteSentenceList) {
            sentenceList.add(sentenceDO.getId());
        }
        //stream流筛选出需要添加的释义
        List<ExampleSentenceDO> addSentenceList = convertExampleSentenceDOs.stream()
                .filter(exampleSentenceDO -> selectSentenceDOList.stream()
                        .noneMatch(convertDO ->
                                Objects.equals(exampleSentenceDO.getContent(), convertDO.getContent()) &&
                                        Objects.equals(exampleSentenceDO.getMeaning(), convertDO.getMeaning())
                        )
                ).collect(Collectors.toList());
        //删除例句
        exampleSentenceMapper.deleteByIds(sentenceList);
        //添加例句
        if (!CollectionUtils.isEmpty(addList)) {
            addSentenceList.forEach((sentenceDO -> {
                sentenceDO.setVocId(id);
                exampleSentenceMapper.insert(sentenceDO);
            }));
        }

        //修改章节-书籍
        List<VocChapBookCommand> relations = command.getRelations();
        List<VocChapBookDO> convertVocChapBookDOs = vocConverter.commands2VocChapBookDOs(relations);
        LambdaQueryWrapper<VocChapBookDO> chapBookDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chapBookDOLambdaQueryWrapper.eq(VocChapBookDO::getVocId, id);
        List<VocChapBookDO> selcetVocChapBookDOS = vocChapBookMapper.selectList(chapBookDOLambdaQueryWrapper);
        //stream流筛选出需要删除的单词-章节-书籍
        List<VocChapBookDO> deletVocChapBookDOList = selcetVocChapBookDOS.stream()
                .filter(vocChapBookDO -> convertVocChapBookDOs.stream()
                        .noneMatch(convertDO ->
                                Objects.equals(vocChapBookDO.getBookId(), convertDO.getBookId()) &&
                                        Objects.equals(vocChapBookDO.getChapterId(), convertDO.getChapterId())
                        )
                ).collect(Collectors.toList());
        ArrayList<Long> vocChaoBookList = new ArrayList<>();
        ArrayList<Long> bookIDList = new ArrayList<>();
        ArrayList<Long> chapterIDList = new ArrayList<>();
        for (VocChapBookDO vocChapBookDO : deletVocChapBookDOList) {
            sentenceList.add(vocChapBookDO.getId());
            bookIDList.add(vocChapBookDO.getBookId());
            if (vocChapBookDO.getChapterId() != null) {
                chapterIDList.add(vocChapBookDO.getChapterId());
            }
        }
        //stream流筛选出需要添加的单词-章节-书籍
        List<VocChapBookDO> addVocChapBookDOList = convertVocChapBookDOs.stream()
                .filter(vocChapBookDO -> selcetVocChapBookDOS.stream()
                        .noneMatch(convertDO ->
                                Objects.equals(vocChapBookDO.getBookId(), convertDO.getBookId()) &&
                                        Objects.equals(vocChapBookDO.getChapterId(), convertDO.getChapterId())
                        )
                ).collect(Collectors.toList());

        //修改删除的章节/书籍的单词数量
        bookIDList.forEach((bookId) -> {
            LambdaUpdateWrapper<VocBookDO> vocBookDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            vocBookDOLambdaUpdateWrapper.eq(VocBookDO::getId, bookId)
                    .setSql("voc_count = voc_count - 1");
            vocBookMapper.update(vocBookDOLambdaUpdateWrapper);
        });
        chapterIDList.forEach((chapterId) -> {
            LambdaUpdateWrapper<VocChapterDO> vocChapDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            vocChapDOLambdaUpdateWrapper.eq(VocChapterDO::getId, chapterId)
                    .setSql("voc_count = voc_count -1");
            vocChapterMapper.update(vocChapDOLambdaUpdateWrapper);

        });
        //删除单词-章节-书籍
        vocChapBookMapper.deleteByIds(vocChaoBookList);
        //添加单词-章节-书籍
        if (!CollectionUtils.isEmpty(addVocChapBookDOList)) {
            //只有插入和修改才会回填id
            addVocChapBookDOList.forEach((vocChapBookDO -> {
                vocChapBookDO.setVocId(id);
                vocChapBookMapper.insert(vocChapBookDO);
                //修改章节单词数量
                if (vocChapBookDO.getCategoryId() != null) {
                    LambdaUpdateWrapper<VocChapterDO> vocChapDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    vocChapDOLambdaUpdateWrapper.eq(VocChapterDO::getId, vocChapBookDO.getChapterId())
                            .setSql("voc_count = voc_count + 1");
                    vocChapterMapper.update(vocChapDOLambdaUpdateWrapper);
                }
                //修改书籍单词数量
                LambdaUpdateWrapper<VocBookDO> vocBookDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                vocBookDOLambdaUpdateWrapper.eq(VocBookDO::getId, vocChapBookDO.getBookId())
                        .setSql("voc_count = voc_count + 1");
                vocBookMapper.update(vocBookDOLambdaUpdateWrapper);
            }));

        }

    }
    @OperateLog(dateType = "单词",operateType =OperateLogConstant.OPERATE_SINGLE_DELETE )
    @Override
    public DeleteVocOperateDTO deleteVocabulary(Long vocId) {
        VocDO vocDO = vocMapper.selectById(vocId);
        int effectiveRow = vocMapper.deleteById(vocId);
        LambdaQueryWrapper<VocMeaningDO> vocMeaningDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vocMeaningDOLambdaQueryWrapper.eq(VocMeaningDO::getVocId,vocId);
        vocMeaningMapper.delete(vocMeaningDOLambdaQueryWrapper);
        LambdaQueryWrapper<ExampleSentenceDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ExampleSentenceDO::getVocId,vocId);
        int delete = exampleSentenceMapper.delete(lambdaQueryWrapper);
        LambdaQueryWrapper<VocChapBookDO> chapBookDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chapBookDOLambdaQueryWrapper.eq(VocChapBookDO::getVocId,vocId);
        List<VocChapBookDO> vocChapBookDOS = vocChapBookMapper.selectList(chapBookDOLambdaQueryWrapper);
        if (vocChapBookDOS==null|| vocChapBookDOS.isEmpty())
        {
            return null;
        }

        vocChapBookMapper.delete(chapBookDOLambdaQueryWrapper);
        LambdaUpdateWrapper<VocBookDO> vocBookDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        vocBookDOLambdaUpdateWrapper.eq(VocBookDO::getId, vocChapBookDOS.get(0).getBookId())
                .setSql("voc_count = voc_count - 1");
        vocBookMapper.update(vocBookDOLambdaUpdateWrapper);
        LambdaUpdateWrapper<VocChapterDO> vocChapDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        vocChapDOLambdaUpdateWrapper.eq(VocChapterDO::getId, vocChapBookDOS.get(0).getChapterId())
                .setSql("voc_count = voc_count -1");
        vocChapterMapper.update(vocChapDOLambdaUpdateWrapper);
        System.out.println("受影响行数: " + effectiveRow);
        DeleteVocOperateDTO deleteVocOperateDTO = vocConverter.toDeleteVocOperateDTO(vocDO);
        return deleteVocOperateDTO;
    }
@Transactional
@OperateLog(dateType = "单词",operateType =OperateLogConstant.OPERATE_BATCH_DELETE )
    @Override
    public List<DeleteVocOperateDTO> deleteVocabularies(BatchDeleteCommand command) {
        if (command==null||command.getIds()==null)
        {
            return null;
        }
        List<Long> ids = command.getIds().stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
        List<Long> bookid = new ArrayList<>();
        List<Long> chapterid = new ArrayList<>();
        List<DeleteVocOperateDTO> deleteVocOperateDTOS = new ArrayList<>();
        if (!ids.isEmpty()) {
//            vocMapper.deleteByIds(ids);
            ids.forEach((vocid) -> {
                //删除单词表中的单词
                DeleteVocOperateDTO deleteVocOperateDTO = new DeleteVocOperateDTO();
                VocDO vocDO = vocMapper.selectById(vocid);
                if (vocDO!=null)
                {
                    deleteVocOperateDTO.setContent(vocDO.getContent());
                }
                deleteVocOperateDTO.setId(vocid);
                deleteVocOperateDTO.setContent(vocDO.getContent());
                deleteVocOperateDTOS.add(deleteVocOperateDTO);
                vocMapper.deleteById(vocid);
                //删除单词释义
                LambdaQueryWrapper<VocMeaningDO> vocMeaningDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
                vocMeaningDOLambdaQueryWrapper.eq(VocMeaningDO::getVocId, vocid);
                vocMeaningMapper.delete(vocMeaningDOLambdaQueryWrapper);
                //删除单词例句
                LambdaQueryWrapper<ExampleSentenceDO> exampleSentenceLambdaQueryWrapper = new LambdaQueryWrapper<>();
                exampleSentenceLambdaQueryWrapper.eq(ExampleSentenceDO::getVocId, vocid);
                exampleSentenceMapper.delete(exampleSentenceLambdaQueryWrapper);
                //删除单词-章节-目录
                LambdaQueryWrapper<VocChapBookDO> chapBookDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
                chapBookDOLambdaQueryWrapper.eq(VocChapBookDO::getVocId, vocid);
                List<VocChapBookDO> vocChapBookDOList = vocChapBookMapper.selectList(chapBookDOLambdaQueryWrapper);
                if (!vocChapBookDOList.isEmpty()) {
                    vocChapBookDOList.forEach((vocChapBookDO) -> {
                        bookid.add(vocChapBookDO.getBookId());
                        chapterid.add(vocChapBookDO.getChapterId());
                    });
                }
                vocChapBookMapper.delete(chapBookDOLambdaQueryWrapper);
            });
            //修改删除的章节/书籍的单词数量
            bookid.forEach((bookId) -> {
                LambdaUpdateWrapper<VocBookDO> vocBookDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                vocBookDOLambdaUpdateWrapper.eq(VocBookDO::getId, bookId)
                        .setSql("voc_count = voc_count - 1");
                vocBookMapper.update(vocBookDOLambdaUpdateWrapper);
            });
            chapterid.forEach((chapterId) -> {
                LambdaUpdateWrapper<VocChapterDO> vocChapDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                vocChapDOLambdaUpdateWrapper.eq(VocChapterDO::getId, chapterId)
                        .setSql("voc_count = voc_count -1");
                vocChapterMapper.update(vocChapDOLambdaUpdateWrapper);
            });
        }
        return deleteVocOperateDTOS;
    }

    @Override
    public List<VocChapBookDTO> getVocRelations(Long vocId) {
        LambdaQueryWrapper<VocChapBookDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VocChapBookDO::getVocId, vocId);
        List<VocChapBookDO> vocChapBookDOS = vocChapBookMapper.selectList(lambdaQueryWrapper);
        return vocConverter.vocChapBookDOs2DTOs(vocChapBookDOS);
    }

    @Override
    public PageDTO<DisplayBookVocDTO> getDisplayBookVocsInfo(AppVocPageRequest pageRequest) {
        String bookId = pageRequest.getBookId();
        Integer pageNum = pageRequest.getPageNum();
        Integer count = pageRequest.getCount();
        String userId = pageRequest.getUserId();
        long userIdLong = Long.parseLong(userId);

        // 分页查询VocChapBookDO列表
        Page<VocChapBookDO> page = pageNum == 0
                ? new Page<>(1, Integer.MAX_VALUE)
                : new Page<>(pageNum, count);

        page = vocChapBookMapper.selectPage(page,
                new LambdaQueryWrapper<VocChapBookDO>()
                        .eq(VocChapBookDO::getBookId, bookId));

        List<VocChapBookDO> vocChapBookDOS = page.getRecords();

        if (CollectionUtils.isEmpty(vocChapBookDOS)) {
            return vocConverter.displayBookVocList2Page(Collections.emptyList(), (long)0);
        }

        // 提取所有vocId (使用selectObjs一次性查询所有ID)
        List<Long> vocIds = vocChapBookDOS.stream()
                .map(VocChapBookDO::getVocId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 并行处理每个vocId (关键优化点)
        List<VocDO> vocDOS = vocIds.parallelStream()
                .map(vocId -> {
                    // 查询单词详情
                    VocDO vocDetail = vocMapper.getVocDetail(vocId, userIdLong);
                    if (vocDetail == null) return null;

                    // 查询例句
                    List<UserVocExampleSentenceDO> examples = userVocExampleSentenceMapper.selectList(
                            new LambdaQueryWrapper<UserVocExampleSentenceDO>()
                                    .eq(UserVocExampleSentenceDO::getVocId, vocId)
                                    .eq(UserVocExampleSentenceDO::getUserId, userId));

                    // 查询收藏状态
                    UserFavoriteDO favorite = userFavoriteMapper.selectOne(
                            new LambdaQueryWrapper<UserFavoriteDO>()
                                    .eq(UserFavoriteDO::getUserId, userId)
                                    .eq(UserFavoriteDO::getVocId, vocId));

                    // 组装数据
                    vocDetail.setFavorite(favorite != null ? 1 : 0);
                    vocDetail.setUserExamples(examples);
                    return vocDetail;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return vocConverter.displayBookVocList2Page(vocDOS, page.getTotal());
    }

    @Override
    public PageDTO<DisplayChapterDTO> getDisplayBookChapterVocsInfo(AppVocPageRequest pageRequest) {
        String bookId = pageRequest.getBookId();
        Integer pageNum = pageRequest.getPageNum();
        Integer count = pageRequest.getCount();
        String userId = pageRequest.getUserId();
        //转换成long
        long userIdLong = Long.parseLong(userId);
        LambdaQueryWrapper<VocChapBookDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VocChapBookDO::getBookId, bookId);




        Page<VocChapBookDO> page = null;
        List<VocChapBookDO> vocChapBookDOS = new ArrayList<>();
        if (pageNum == 0) {
            page = new Page<>(1, Integer.MAX_VALUE);
            vocChapBookDOS=  vocChapBookMapper.selectList(page, queryWrapper);
        } else {
            page=new Page<>(pageRequest.getPageNum(), pageRequest.getCount());
            vocChapBookDOS=    vocChapBookMapper.selectList(page, queryWrapper);
        }





        Set<Long> set = new HashSet<>();
        for (VocChapBookDO vocChapBookDO : vocChapBookDOS) {
            Long chapterId = vocChapBookDO.getChapterId();
            set.add(chapterId);
        }

        List<VocChapterDO> vocChapters = new ArrayList<>();
        for (Long chapterId : set) {
            LambdaQueryWrapper<VocChapterDO> queryWrapper100 = new LambdaQueryWrapper<>();
            queryWrapper100.eq(VocChapterDO::getId, chapterId);
            VocChapterDO vocChapterDO = vocChapterMapper.selectOne(queryWrapper100);
            //查单词
            LambdaQueryWrapper<VocChapBookDO> queryWrapper101 = new LambdaQueryWrapper<>();
            queryWrapper101.eq(VocChapBookDO::getChapterId, chapterId);
            List<VocChapBookDO> vocChapBookDOS1 = vocChapBookMapper.selectList(queryWrapper101);
            List<VocDO> vocDOS = new ArrayList<>();
            for (VocChapBookDO vocChapBookDO1 : vocChapBookDOS1) {
                Long vocId = vocChapBookDO1.getVocId();
                VocDO vocDetail = vocMapper.getVocDetail(vocId, userIdLong);
                if (vocDetail != null) {
                    LambdaQueryWrapper<UserVocExampleSentenceDO> queryWrapper20 = new LambdaQueryWrapper<>();
                    queryWrapper20.eq(UserVocExampleSentenceDO::getVocId, vocId)
                            .eq(UserVocExampleSentenceDO::getUserId, userId);
                    List<UserVocExampleSentenceDO> userVocExampleSentenceDOS = userVocExampleSentenceMapper.selectList(queryWrapper20);
                    //赋值
                    LambdaQueryWrapper<UserFavoriteDO> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(UserFavoriteDO::getUserId, userId)
                            .eq(UserFavoriteDO::getVocId, vocId);
                    UserFavoriteDO userFavoriteDO = userFavoriteMapper.selectOne(queryWrapper1);
                    if (userFavoriteDO != null) {
                        vocDetail.setFavorite(1);
                    } else {
                        vocDetail.setFavorite(0);
                    }

                    vocDetail.setUserExamples(userVocExampleSentenceDOS);
                    vocDOS.add(vocDetail);

                }

            }
            if (vocChapterDO != null) {
                vocChapterDO.setVocs(vocDOS);
            }
            vocChapters.add(vocChapterDO);

        }
        PageDTO<DisplayChapterDTO> displayChapterDTOPageDTO = vocConverter.displayChapterVocList2Page(vocChapters, page.getTotal());
        return displayChapterDTOPageDTO;
    }

    @Override
    public VocDTO getVocDetail(Long vocId, Long userId) {

        VocDO vocDetail = vocMapper.getVocDetail(vocId, userId);
        if (vocDetail != null) {
            LambdaQueryWrapper<UserVocExampleSentenceDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserVocExampleSentenceDO::getVocId, vocId)
                    .eq(UserVocExampleSentenceDO::getUserId, userId);
            List<UserVocExampleSentenceDO> userVocExampleSentenceDOS = userVocExampleSentenceMapper.selectList(queryWrapper);
            //赋值
            LambdaQueryWrapper<UserFavoriteDO> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(UserFavoriteDO::getUserId, userId)
                    .eq(UserFavoriteDO::getVocId, vocId);
            UserFavoriteDO userFavoriteDO = userFavoriteMapper.selectOne(queryWrapper1);
            if (userFavoriteDO != null) {
                vocDetail.setFavorite(1);
            } else {
                vocDetail.setFavorite(0);
            }


            vocDetail.setUserExamples(userVocExampleSentenceDOS);
            return vocConverter.vocDO2DTO(vocDetail);
        } else {
            return null;
        }
    }

    @Override
    public UserBookStatisticsDTO getUserChooseCountInBook(Long userId, Long bookId) {
        return null;
    }

    @Override
    public void vocExcelValidate(MultipartFile file) throws IOException {

        // 读取模板文件内容
//        InputStream templateStream = new ClassPathResource("templates/单词上传模版.xlsx").getInputStream();
        ClassPathResource classPathResource = new ClassPathResource("templates/单词上传模版.xlsx");
        if (!classPathResource.exists()) {
            throw new FileNotFoundException("模板文件不存在: " + classPathResource.getPath());
        }
        InputStream templateStream = classPathResource.getInputStream();
        InputStream uploadStream = file.getInputStream();
        //Excel文件头的是否与模版文件的文件头数量，内容是否相同
        class MyHeaderReadListener extends AnalysisEventListener<VocExcelDTO> {
            List<String> headers = new ArrayList<>(); // 存储表头内容
            int headCount;

            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                System.out.println("读取表头处理方法");
                this.headCount = headMap.size();
                // 按列索引顺序存储表头
                for (int i = 0; i < headCount; i++) {
                    headers.add(headMap.get(i));
                }
            }

            @Override
            public void invoke(VocExcelDTO vocExcelDTO, AnalysisContext analysisContext) {
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
            public void validateHeaders(MyHeaderReadListener uploaded) {


                // 1. 验证表头数量
                if (this.headCount != uploaded.headCount) {
                    throw new RuntimeException("表头数量不一致（模板:" + this.headCount + "列，上传文件:" + uploaded.headCount + "列）");
                }

                // 2. 逐列比较表头内容
                for (int i = 0; i < this.headCount; i++) {
                    String templateHeader = this.headers.get(i).trim();
                    String uploadedHeader = uploaded.headers.get(i).trim();
                    System.out.println("模板文件名：" + templateHeader + "-----上传文件名：" + uploadedHeader);
                    if (!templateHeader.equals(uploadedHeader)) {
                        throw new RuntimeException("第" + (i + 1) + "列表头不一致（模板:'" + templateHeader + "', 上传文件:'" + uploadedHeader + "'）");
                    }
                }
                System.out.println("表头非常匹配");
            }
        }
        MyHeaderReadListener templateFileListener = new MyHeaderReadListener();
        MyHeaderReadListener myFileListener = new MyHeaderReadListener();

        ExcelReaderBuilder templateFile = EasyExcel.read(templateStream, VocExcelDTO.class, templateFileListener).excelType(ExcelTypeEnum.XLSX);
        ExcelReaderBuilder myFile = EasyExcel.read(uploadStream, VocExcelDTO.class, myFileListener).excelType(ExcelTypeEnum.XLSX);
        // 同步读取模板文件
        templateFile.sheet().doReadSync();
        // 同步读取上传文件
        myFile.sheet().doReadSync();
        // 验证表头
        templateFileListener.validateHeaders(myFileListener);

        EasyExcel.read(file.getInputStream(), VocExcelDTO.class, new ReadListener<VocExcelDTO>() {
            /**
             * 单次缓存的数据量
             */

            @Override
            public void invoke(VocExcelDTO data, AnalysisContext context) {


                if (data != null) {    //判断data 中的字符串类型的值是否为空
                    if (StringUtils.isAnyBlank(data.getBookInfos(), data.getExampleSentences(), data.getUkPronounciation(),
                            data.getUsPronounciation(), data.getInterpretations(), data.getContent(), data.getUkPhonetic(), data.getUsPhonetic())) {
                        throw new ExcelParseException(ResultCodeEnum.PARAM_ERROR, "单元格中有空值");
                    }


                    //将字符串转化为对象列表
                    String stringInterpretation = data.getInterpretations();
                    if (stringInterpretation != null && !stringInterpretation.isEmpty()) {
                        String[] arrayInterpretation = stringInterpretation.split("\n");
                        for (String s : arrayInterpretation) {
                            if (!validateWordFormat(s)) {
                                throw new ExcelParseException(ResultCodeEnum.PARAM_ERROR, "单词释义格式不为词性.词义" + s);
                            }
                        }
                    }
                    String stringExampleSentence = data.getExampleSentences();
                    if (stringExampleSentence !=null&& !stringInterpretation.isEmpty()) {
                        String[] exampleArray = stringExampleSentence.split("\n");
                        for (int i = 0; i < exampleArray.length; i += 2) {

                            if (!validateEngExampleFormat(exampleArray[i])) {
                                throw new ExcelParseException(ResultCodeEnum.PARAM_ERROR, "单词例句不为英文例句\n例句中文释义");
                            }
                            if (!validateChinesExampleFormat(exampleArray[i + 1])) {
                                throw new ExcelParseException(ResultCodeEnum.PARAM_ERROR, "单词例句不为英文例句\n例句中文释义");
                            }
                        }
                    }


                    String stringBookInfos = data.getBookInfos();
                    if (stringBookInfos != null && !stringBookInfos.isEmpty()) {
                        String[] arrayChapBook = stringBookInfos.split("\n");
                        for (String chapBook : arrayChapBook) {
                            chapBook = chapBook.trim();
                            String[] chapBookList = Arrays.stream(chapBook.split("#"))
                                    .map(String::trim)  // 去除前后空格
                                    .filter(str -> !str.isEmpty())  // 过滤空字符串
                                    .toArray(String[]::new);
                            //查询bookid和chapterid
                            if (chapBookList.length == 1) {
                                LambdaQueryWrapper<VocBookDO> vocBookDOQueryWrapper = new LambdaQueryWrapper<>();
                                vocBookDOQueryWrapper.eq(VocBookDO::getName, chapBookList[0]);
                                List<VocBookDO> vocBookDOS = vocBookMapper.selectList(vocBookDOQueryWrapper);
                                if (vocBookDOS == null) {
                                    throw new ExcelParseException(ResultCodeEnum.PARAM_ERROR, "单词所属书籍不存在");

                                }
                            } else {
                                LambdaQueryWrapper<VocChapterDO> vocBookDOQueryWrapper = new LambdaQueryWrapper<>();
                                vocBookDOQueryWrapper.eq(VocChapterDO::getChapterName, chapBookList[1]).eq(VocChapterDO::getBookName, chapBookList[0]);
                                VocChapterDO vocChapterDO = vocChapterMapper.selectOne(vocBookDOQueryWrapper);

                                if (vocChapterDO == null) {
                                    throw new ExcelParseException(ResultCodeEnum.PARAM_ERROR, "单词所属书籍或章节不存在");
                                }
                            }

                        }
                    }
                }
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
            }
            //正则表达式
            public static boolean validateWordFormat(String word) {
                // 正则表达式解释：
                // ^ 字符串开始
                // [a-zA-Z]+ 一个或多个字母（词性缩写）
                // \\. 必须包含点号
                // .+ 点号后跟随一个或多个任意字符（词义解释）
                // $ 字符串结束
                return Pattern.matches("^[a-z]+\\.\\s*[a-zA-Z0-9\\u4e00-\\u9fa5]+$", word);
            }
            /**
             * 校验例句格式是否为"英文例句\n例句中文释义"
             * @param example 待校验的例句
             * @return 是否符合格式要求
             */
            public static boolean validateEngExampleFormat(String example) {
                // 检查是否包含换行符且换行符前后都有内容
                if (example == null || example.isEmpty()) {
                    return false;
                }
                // 必须有且只有两部分（英文和中文），且两部分都不为空
                return Pattern.matches("^[a-zA-Z0-9]+\\s+[a-zA-Z0-9\\s.,!?]+$", example);
            }
            public static boolean validateChinesExampleFormat(String example) {
                // 检查是否包含换行符且换行符前后都有内容
                if (example == null || example.isEmpty()) {
                    return false;
                }
                // 必须有且只有两部分（英文和中文），且两部分都不为空
                return Pattern.matches("^[a-zA-Z0-9]+\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]+$", example);
            }


        }).sheet().doReadSync();
    }

     @Transactional
     @OperateLog(dateType = "单词",operateType =OperateLogConstant.OPERATE_EXCEL_ADD )
    @Override
    public ExcelAddOperateDTO addVocExcel(MultipartFile file, Long userId) throws IOException {
//        fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭

        final Integer[] count = {0};
        EasyExcel.read(file.getInputStream(), VocExcelDTO.class, new ReadListener<VocExcelDTO>() {
            /**
             * 单次缓存的数据量
             */
            public static final int BATCH_COUNT = 100;
            /**
             *临时存储
             */
            private List<VocDO> vocDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            private List<List<VocMeaningDO>> vocMeaningList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            private List<List<ExampleSentenceDO>> exampleSentenceList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            private List<List<VocChapBookDO>> vocChapBookDOList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(VocExcelDTO data, AnalysisContext context) {

                VocDO vocData = vocConverter.vocExcelDTO2VocDO(data);
                List<VocChapBookDO> listVocChapBookDOS = new ArrayList<>();
                List<ExampleSentenceDO> listExampleSentenceDO = new ArrayList<>();
                List<VocMeaningDO> listVocMeaningDO = new ArrayList<>();


                //将字符串转化为对象列表
                String stringInterpretation = data.getInterpretations();
                String stringExampleSentence = data.getExampleSentences();
                String stringBookInfos = data.getBookInfos();
                if (stringInterpretation != null && !stringInterpretation.isEmpty()) {
                    String[] arrayInterpretation = stringInterpretation.split("\n");
                    for (String interpretation : arrayInterpretation) {
                        VocMeaningDO vocMeaningDO = new VocMeaningDO();
                        interpretation = interpretation.trim();
                        if (interpretation.isEmpty()) {
                            vocMeaningDO.setType(null);
                            vocMeaningDO.setInterContent(null);
                        } else {
                            String[] meaning = Arrays.stream(interpretation.split(".", 2))
                                    .map(String::trim).toArray(String[]::new);
                            vocMeaningDO.setType(meaning[0].trim());
                            vocMeaningDO.setInterContent(meaning.length > 1 ? meaning[1].trim() : null);
                        }
                        listVocMeaningDO.add(vocMeaningDO);

                    }
                }

                if (stringExampleSentence != null && !stringExampleSentence.isEmpty()) {
                    String[] arrayExample = stringExampleSentence.split("\n");
                    for (int i = 0; i < arrayExample.length; i += 2) {
                        ExampleSentenceDO sentenceDO = new ExampleSentenceDO();
                        sentenceDO.setContent(arrayExample[i].trim());
                        sentenceDO.setMeaning(arrayExample[i + 1].trim());
                        listExampleSentenceDO.add(sentenceDO);
                    }

                }
                if (stringBookInfos != null && !stringBookInfos.isEmpty()) {
                    String[] arrayChapBook = stringBookInfos.split("\n");
                    for (String chapBook : arrayChapBook) {
                        VocChapBookDO vocChapBookDO = new VocChapBookDO();
                        chapBook = chapBook.trim();
                        String[] chapBookList = Arrays.stream(chapBook.split("#"))
                                .map(String::trim)  // 去除前后空格
                                .filter(str -> !str.isEmpty())  // 过滤空字符串
                                .toArray(String[]::new);
                        //查询bookid和chapterid
                        if (chapBookList.length == 1) {
                            VocBookDO fristvocBookDO =new VocBookDO();
                            LambdaQueryWrapper<VocBookDO> vocBookDOQueryWrapper = new LambdaQueryWrapper<>();
                            vocBookDOQueryWrapper.eq(VocBookDO::getName,chapBookList[0]);
                            List<VocBookDO> vocBookDOS = vocBookMapper.selectList(vocBookDOQueryWrapper);
                            if (vocBookDOS!=null)
                            {
                                fristvocBookDO=vocBookDOS.get(0);

                            }
                            vocChapBookDO.setBookId(fristvocBookDO.getId());
                            vocChapBookDO.setBookName(chapBookList[0]);
                            vocChapBookDO.setChapterId(null);
                            vocChapBookDO.setChapterName(null);

                        }
                        else {
                            LambdaQueryWrapper<VocChapterDO> vocBookDOQueryWrapper = new LambdaQueryWrapper<>();
                            vocBookDOQueryWrapper.eq(VocChapterDO::getChapterName,chapBookList[1]).eq(VocChapterDO::getBookName,chapBookList[0]);
                            VocChapterDO vocChapterDO = vocChapterMapper.selectOne(vocBookDOQueryWrapper);

                            if (vocChapterDO!=null)
                            {   vocChapBookDO.setChapterId(vocChapterDO.getId());
                                vocChapBookDO.setBookId(vocChapterDO.getBookId());
                                vocChapBookDO.setChapterName(chapBookList[0]);
                                vocChapBookDO.setChapterName(chapBookList[1]);
                            }
                        }
                        listVocChapBookDOS.add(vocChapBookDO);

                    }
                }

                //todo:批量插入 还是调用单个插入的方法
                vocDataList.add(vocData);
                vocMeaningList.add(listVocMeaningDO);
                exampleSentenceList.add(listExampleSentenceDO);
                vocChapBookDOList.add(listVocChapBookDOS);


                if (vocDataList.size() >= BATCH_COUNT) {
                    vocMapper.insert(vocDataList);
                    for (int i = 0; i <vocDataList.size() ; i++) {
                        Long id = vocDataList.get(i).getId();


                        //添加释义
                        List<VocMeaningDO> vocMeaningDOs = vocMeaningList.get(i);
                        if (!CollectionUtils.isEmpty(vocMeaningDOs)) {
                            //只有插入和修改才会回填id
                            vocMeaningDOs.forEach((vocMeaningDO -> {
                                vocMeaningDO.setVocId(id);
                                vocMeaningMapper.insert(vocMeaningDO);
                            }));
                        }

                        //添加例句
                        List<ExampleSentenceDO> exampleSentenceDOs =exampleSentenceList.get(i);
                        if (!CollectionUtils.isEmpty(exampleSentenceDOs)) {
                            //只有插入和修改才会回填id

                            exampleSentenceDOs.forEach((exampleSentenceDO -> {
                                exampleSentenceDO.setVocId(id);
                                exampleSentenceMapper.insert(exampleSentenceDO);
                            }));
                        }

                        //添加
                        List<VocChapBookDO> vocChapBookDOs = vocChapBookDOList.get(i);
                        if (!CollectionUtils.isEmpty(vocChapBookDOs)) {
                            //只有插入和修改才会回填id

                            vocChapBookDOs.forEach((vocChapBookDO -> {
                                vocChapBookDO.setVocId(id);
                                vocChapBookMapper.insert(vocChapBookDO);

                                //修改章节单词数量
                                if (vocChapBookDO.getCategoryId() != null) {
                                    LambdaUpdateWrapper<VocChapterDO> vocChapDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                                    vocChapDOLambdaUpdateWrapper.eq(VocChapterDO::getId, vocChapBookDO.getChapterId())
                                            .setSql("voc_count = voc_count + 1");
                                    vocChapterMapper.update(vocChapDOLambdaUpdateWrapper);
                                }
                                //修改书籍单词数量
                                LambdaUpdateWrapper<VocBookDO> vocBookDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                                vocBookDOLambdaUpdateWrapper.eq(VocBookDO::getId, vocChapBookDO.getBookId())
                                        .setSql("voc_count = voc_count + 1");
                                vocBookMapper.update(vocBookDOLambdaUpdateWrapper);
                            }));
                        }

                    }
                    count[0] +=vocDataList.size();

                    // 存储完成清理 list
                    vocDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                    vocMeaningList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                    exampleSentenceList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                    vocChapBookDOList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {

                vocMapper.insert(vocDataList);

                for (int i = 0; i <vocDataList.size() ; i++) {
                    Long id = vocDataList.get(i).getId();


                    //添加释义
                    List<VocMeaningDO> vocMeaningDOs = vocMeaningList.get(i);
                    if (!CollectionUtils.isEmpty(vocMeaningDOs)) {
                        //只有插入和修改才会回填id
                        vocMeaningDOs.forEach((vocMeaningDO -> {
                            vocMeaningDO.setVocId(id);
                            vocMeaningMapper.insert(vocMeaningDO);
                        }));
                    }

                    //添加例句
                    List<ExampleSentenceDO> exampleSentenceDOs =exampleSentenceList.get(i);
                    if (!CollectionUtils.isEmpty(exampleSentenceDOs)) {
                        //只有插入和修改才会回填id

                        exampleSentenceDOs.forEach((exampleSentenceDO -> {
                            exampleSentenceDO.setVocId(id);
                            exampleSentenceMapper.insert(exampleSentenceDO);
                        }));
                    }

                    //添加
                    List<VocChapBookDO> vocChapBookDOs = vocChapBookDOList.get(i);
                    if (!CollectionUtils.isEmpty(vocChapBookDOs)) {
                        //只有插入和修改才会回填id

                        vocChapBookDOs.forEach((vocChapBookDO -> {
                            vocChapBookDO.setVocId(id);
                            vocChapBookMapper.insert(vocChapBookDO);

                            //修改章节单词数量
                            if (vocChapBookDO.getCategoryId() != null) {
                                LambdaUpdateWrapper<VocChapterDO> vocChapDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                                vocChapDOLambdaUpdateWrapper.eq(VocChapterDO::getId, vocChapBookDO.getChapterId())
                                        .setSql("voc_count = voc_count + 1");
                            }
                            //修改书籍单词数量
                            LambdaUpdateWrapper<VocBookDO> vocBookDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                            vocBookDOLambdaUpdateWrapper.eq(VocBookDO::getId, vocChapBookDO.getBookId())
                                    .setSql("voc_count = voc_count + 1");
                        }));

                    }
                }
                count[0] +=vocDataList.size();
            }
        }).sheet().doRead();

        ExcelAddOperateDTO excelAddOperateDTO = new ExcelAddOperateDTO();
        excelAddOperateDTO.setFileName(file.getName());
        excelAddOperateDTO.setTotalCount(count[0]);
        return excelAddOperateDTO;
    }

    @Override
    public DeleteVocFileOperateDTO deleteFile(Long id, String type, String name) {
        //创建返回对象
        DeleteVocFileOperateDTO deleteVocFileOperateDTO = new DeleteVocFileOperateDTO();
        VocDO vocDO = vocMapper.selectById(id);
        if (vocDO==null)
        {
            return null;
        }
        int total ;
        LambdaUpdateWrapper<VocDO> vocDOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if (id == null || type == null || name == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 只允许us或uk类型
        if (!"us".equals(type) && !"uk".equals(type)) {
            throw new IllegalArgumentException("type参数只能是us或uk");
        }
        if ("us".equals(type)) {
            vocDOLambdaUpdateWrapper.eq(VocDO::getId, id).set(VocDO::getUsPronounciation, null);
        }
        if ("uk".equals(type)) {
            vocDOLambdaUpdateWrapper.eq(VocDO::getId, id).set(VocDO::getUkPronounciation, null);
        }

        total = vocMapper.update(vocDOLambdaUpdateWrapper);
        deleteVocFileOperateDTO.setVocId(id);
        deleteVocFileOperateDTO.setContent(vocDO.getContent());
        deleteVocFileOperateDTO.setType(type);
        deleteVocFileOperateDTO.setFileName(name);

        if (total == 1) {

            return deleteVocFileOperateDTO;
        } else
            return null;

    }

    @Override
    public DeleteVocRelationOperateDTO deleteVocRelation(Long id) {
        int effectiveRow = vocChapBookMapper.deleteById(id);
        System.out.println("受影响行数: " + effectiveRow);
        return null;
    }

    @Override
    public DeleteInterpretationOperateDTO deleteInterpretation(Long id) {
        int effectiveRow = vocMeaningMapper.deleteById(id);
        System.out.println("受影响行数: " + effectiveRow);
        return null;
    }

    @Override
    public DeleteVocExampleOperateDTO deleteExample(Long id) {
        int effectiveRow = exampleSentenceMapper.deleteById(id);
        System.out.println("受影响行数: " + effectiveRow);
        return null;
    }
}
